﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FMALog
{
    public class LogManager
    {
        private String logPath { get; set; }
        private LogMode logMode { get; set; }

        public LogManager(String logPath)
        {
            this.logPath = logPath;
            try
            {
                String logModeStr = System.Configuration.ConfigurationManager.AppSettings["logMode"];
                logMode = (LogMode)Enum.Parse(typeof(LogMode), logModeStr);
            }
            catch
            {
                logMode = LogMode.All;
            }
        }

        public LogManager()
        {
            logPath = System.Configuration.ConfigurationManager.AppSettings["logPath"];
            try
            {
                String logModeStr = System.Configuration.ConfigurationManager.AppSettings["logMode"];
                logMode = (LogMode)Enum.Parse(typeof(LogMode), logModeStr);
            }
            catch
            {
                logMode = LogMode.All;
            }
        }
        public void WriteLog(String message, LogType type)
        {
            WriteLog(new Log() { message = message, type = type });
        }
        public void WriteLog(Exception ex)
        {
            WriteLog(new Log() { exception = ex });
        }
        public void WriteLog(Log log)
        {
            string fileName = DateTime.Now.ToShortDateString();
            switch (log.type)
            {
                case LogType.Error: fileName += "-Error"; writeLog(log, fileName); break;
                case LogType.Info: if (logMode == LogMode.All) { fileName += "-Info"; writeLog(log, fileName); } break;
                case LogType.Warning: if (logMode == LogMode.All || logMode == LogMode.ErrorAndWarning) { fileName += "-Warning"; writeLog(log, fileName); } break;
            }
        }

        public void WriteInfoLog(String message)
        {
            this.WriteLog(message, LogType.Info);
        }
        public void WriteErrorLog(String message)
        {
            this.WriteLog(message, LogType.Error);
        }
        public void WriteWarningLog(String message)
        {
            this.WriteLog(message, LogType.Warning);
        }

        private void writeLog(Log log, String fileName)
        {
            using (StreamWriter f = File.AppendText(logPath + "\\" + fileName + ".log"))
            {
                f.WriteLine(log.ToString());
            }
        }
    

    }
}
